var ctx = window.daijia.ctx;

var offset = 0;
var limit = 20;
var pagingLimit = 20;//显示分页时的条数
var currentTotalElements = 0;//当前显示总条数


var pageLoading = true;//是否能滚动加载
var hasShowPages = false;//是否已显示分页
var firstLoadPages = true;//分页初始化时 不自动加载


var thisButton;

function deleteCouponRule() {
    $.post(ctx + '/couponrule/delete', {'id': thisButton.attr("data-value")}, function (data) {
        if (data.success) {
            $.scojs_message('优惠劵删除成功', $.scojs_message.TYPE_OK);
            initdata(false);
        } else {
            $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
        }
    }, 'json');
}

function lapsedCouponRule() {
    $.post(ctx + '/couponrule/lapsed', {'id': thisButton.attr("data-value")}, function (data) {
        if (data.success) {
            $.scojs_message('操作成功', $.scojs_message.TYPE_OK);
            initdata(false);
        } else {
            $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
        }
    }, 'json');
}

$(document).ready(function () {

    initdata(false);

    //删除活动
    $(document).on("click", ".deletethis", function () {
        var id = $(this).attr("data-value");
        if (window.confirm('确认要删除吗？（删除后客户相关优惠券将全部删除）')) {
            $.post(ctx + '/couponrule/delete', {'id': id}, function (data) {
                if (data.success) {
                    $.scojs_message("已删除", $.scojs_message.TYPE_OK);
                    initdata(false);
                } else {
                    $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                }
            });
        }
    });

    $(document).on("click", ".lapsedthis", function () {
        var id = $(this).attr("data-value");
        if (window.confirm('确认要失效吗？')) {
            $.post(ctx + '/couponrule/lapsed', {'id': id}, function (data) {
                if (data.success) {
                    $.scojs_message("已失效", $.scojs_message.TYPE_OK);
                    initdata(false);
                } else {
                    $.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
                }
            });
        }
    });


    //滚动
    $(window).scroll(function () {
        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
        //$(window).height()获取当前窗体的高度
        //$(document).height()获取当前文档的高度
        var bot = 0; //bot是底部距离的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
            //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
            if (pageLoading) {
                pageLoading = false;
                offset += limit;
                initdata(true);
            }
        }
    });

});


function initdata(isappend) {

    $.ajax({
        url: ctx + '/couponrule/listData',
        type: 'GET',
        async: false,
        dataType: 'json',
        data: {
            "pager.offset": offset,
            "limit": limit,
        },
        success: function (result) {
            var newcontent = '';
            var totalElements = result.totalElements;

            if (totalElements > 0) {


                $(result.content).each(function (index, data) {
                    var statusColor = "";
                    var mainButton = "";
                    var selectButton = "";
                    statusColor = "btn-primary";
                    mainButton = "<a href='" + ctx + "/couponrule/mass/" + data.id + "' class='btn btn-primary btn-xs'>生成优惠劵</a>";
                    if (!data.lapsed) {
                        selectButton += "<li><a href='javascript:;' data-value='" + data.id + "' class='btn-link lapsedthis'>失效</a></li>";
                    }
                    selectButton += "<li><a href='javascript:;' data-value='" + data.id + "' class='btn-link deletethis'>删除</a></li>";
                    selectButton += "<li><a href='" + ctx + "/couponrule/coupon/" + data.id + "' class='btn-link'>查看已生成优惠劵</a></li>";

                    var allButton = "<div class='btn-group'>" +
                        mainButton +
                        "<button type='button' class='btn " + statusColor + " btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>" +
                        "<span class='caret'></span>" +
                        "<span class='sr-only'>Toggle Dropdown</span>" +
                        "</button>" +
                        "<ul class='dropdown-menu' role='menu'>" +
                        selectButton +
                        "</ul>" +
                        "</div>";
                    var timeStatus;
                    if (data.lapsed) {
                        timeStatus = "<td><span style='color:#8B2252;font-weight:700;'>已失效</span></td>";
                    } else if (data.timeStatus == 0) {
                        timeStatus = "<td><span style='color:#EE00EE;font-weight:700;'>未开始</span></td>";
                    } else if (data.timeStatus == 1) {
                        timeStatus = "<td><span style='color:#66CD00;font-weight:700;'>使用中</span></td>";
                    } else if (data.timeStatus == 2) {
                        timeStatus = "<td><span style='color:red;font-weight:700;'>已过期</span></td>";
                    }
                    var companyId;
                    if (mainCompany) {
                        if (data.company) {
                            companyId = "<td>" + data.company.abbreviation + "</td>";
                        } else {
                            companyId = "<td>无</td>";
                        }
                    }
                    var couponRuleType;
                    if (data.type == 0) {
                        couponRuleType = "<td>折扣：<span style='color:red;font-weight:700;'>" + data.discount + "</span></td>";
                    } else if (data.type == 1) {
                        couponRuleType = "<td>抵扣：<span style='color:#ff950b;font-weight:700;'>" + data.money + "</span></td>";
                    }
                    var each;
                    if (data.eachLimit == 0) {
                        each = "<td>不限量</td>";
                    } else {
                        each = "<td>" + data.eachLimit + "</td>";
                    }
                    var couponType;
                    if (data.couponType == "paotui") {
                        couponType = "<td>跑腿</td>";
                        console.debug(data.couponType);
                        console.debug(data.couponTypeId);
                        console.debug(data.couponTypeName);
                        if (data.couponTypeId != null) {
                            couponType += "<td>" + data.couponTypeName + "</td>";
                        } else {
                            couponType += "<td>-</td>";
                        }
                    } else {
                        if (data.couponType == "daijia") {
                            couponType = "<td>代驾</td>";
                        } else if (data.couponType == "zhuanche") {
                            couponType = "<td>专车</td>";
                        } else if (data.couponType == "freight") {
                            couponType = "<td>货运</td>";
                        } else if (data.couponType == "xiche") {
                            couponType = "<td>洗车</td>";
                        } else if (data.couponType == "pinche") {
                            couponType = "<td>拼车</td>";
                        } else if (data.couponType == "zhuanxian") {
                            couponType = "<td>快车</td>";
                        } else if (data.couponType == "gasstation") {
                            couponType = "<td>加油站</td>";
                        } else if (data.couponType == "all") {
                            couponType = "<td>专车，快车</td>";
                        } else {
                            couponType = "<td>-</td>";
                        }
                        couponType += "<td>-</td>";
                    }
                    var end;
                    if (data.end == null) {
                        end = "<td>不限</td>";
                    } else {
                        end = "<td>" + (new Date(data.end).Format("yyyy-MM-dd")) + "</td>";
                    }

                    newcontent += "<tr class='grid-data tr-hui' style='display:none;'>" +
                        "<td>" + allButton + "</td>" +
                        "<td>" + data.title + "</td>" +
                        timeStatus +
                        "<td>" + data.code + "</td>" +
                        companyId +
                        couponRuleType +
                        couponType +
                        "<td>" + data.number + "</td>" +
                        each +
                        "<td>" + (new Date(data.start).Format("yyyy-MM-dd")) + "</td>" +
                        end +
                        "<td>" + allButton + "</td>" +
                        "</tr>";
                });


            }

//        	hideLoading();

            if (!isappend) {
                $(".table tbody .grid-data").remove();
            }
            $(".table tbody").append(newcontent);

            $(".table tbody .grid-data").each(function (index, element) {
                $(element).fadeIn(200 + (index * 35));
            });


            if (!hasShowPages) {
                if (!isappend) {
                    currentTotalElements = result.content.length;
                    pageLoading = true;
                } else {
                    if (currentTotalElements < totalElements) {
                        currentTotalElements += result.content.length;
                        pageLoading = true;
                    } else {
                        pageLoading = false;
                    }
                }
            }

            if (hasShowPages) {
                firstLoadPages = true;
                $(".pageshow li a").html("共" + totalElements + " 条数据");
                $(".pagedata").paging(totalElements, {
                    format: '[< ncnnn >]',
                    perpage: pagingLimit,
                    page: (offset / limit) + 1,
                    onSelect: function (page) {
                        limit = pagingLimit;
                        offset = (page - 1) * limit;
                        if (!firstLoadPages) {
                            initdata(false);
                        }
                        firstLoadPages = false;
                        return false;
                    },
                    onFormat: function (type) {
                        switch (type) {
                            case 'block': // n and c
                                if (!this.active)
                                    return '';
                                else if (this.value != this.page)
                                    return '<li><a href="#">' + this.value + '</a></li>';
                                return '<li class="active"><a href="#">' + this.value + '</a></li>';
                            case 'next': // >
                                return '<li><a href="#">&rsaquo;</a><li>';
                            case 'prev': // <
                                return '<li><a href="#">&lsaquo;</a><li>';
                            case 'first': // [
                                return '<li><a href="#">&laquo;</a><li>';
                            case 'last': // ]
                                return '<li><a href="#">&raquo;</a></li>';
                        }
                    }
                });

            } else {
                //滚动达到pagingLimit条开始显示分页
                if (currentTotalElements == pagingLimit) {

                    pageLoading = false;
                    hasShowPages = true;

                    $(".pageshow").show();
                    $(".pagedata").show();
                    $(".pageshow li a").html("共" + totalElements + " 条数据");
                    $(".pagedata").paging(totalElements, {
                        format: '[< ncnnn >]',
                        perpage: pagingLimit,
                        onSelect: function (page) {
                            limit = pagingLimit;
                            offset = (page - 1) * limit;
                            if (!firstLoadPages) {
                                initdata(false);
                            }
                            firstLoadPages = false;
                            return false;
                        },
                        onFormat: function (type) {
                            switch (type) {
                                case 'block': // n and c
                                    if (!this.active)
                                        return '';
                                    else if (this.value != this.page)
                                        return '<li><a href="#">' + this.value + '</a></li>';
                                    return '<li class="active"><a href="#">' + this.value + '</a></li>';
                                case 'next': // >
                                    return '<li><a href="#">&rsaquo;</a><li>';
                                case 'prev': // <
                                    return '<li><a href="#">&lsaquo;</a><li>';
                                case 'first': // [
                                    return '<li><a href="#">&laquo;</a><li>';
                                case 'last': // ]
                                    return '<li><a href="#">&raquo;</a></li>';
                            }
                        }
                    });

                }
            }

        }
    });

}

function showLoading() {
    if ($('#loadblacklayer').length == 0) {
        var dw = $(".table").width();
        var dh = $(".table").height();
        var backlayer = "<div id='loadblacklayer'><div style='margin-top:" + (dh / 2) + "px;margin-left:" + (dw / 2) + "px;'><img src='" + ctx + "/assets/css/images/loading.gif' /></div></div>"
        $(".table tbody").append(backlayer);
        $('#loadblacklayer').css({
            "z-index": "9",
            "background": "#000",
            "opacity": "0.5",
            "position": 'absolute',
            "top": 0,
            "width": dw,
            "height": dh
        });
    }
}

function hideLoading() {
    if ($('#loadblacklayer').length > 0) {
        $('#loadblacklayer').remove();
    }
}

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
